	/*
	 * Function initializes validation, calls function to create table 
	 */
	$(document).ready(function() {
		
	    /*
	     * Function to create table
	     */	
		refreshMyTable();
    	
		/*
		 * Initialize form validations
		 */
    	$('#insertForm').validate({
            rules: {
            	
                mdrFname: {
                    maxlength: 15,
                    required: true
                },
                mdrMname: {
                    maxlength: 15,
                    required: true
                },mdrFname: {
                    maxlength: 15,
                    required: true
                },
                mdrLname: {
                    maxlength: 15,
                    required: true
                },
                mdrAddress: {
                    maxlength: 15,
                    required: true
                },
                mdrCity: {
                    maxlength: 15,
                    required: true
                },
                mdrState: {
                    maxlength: 15,
                    required: true
                },
                mdrCountry: {
                    maxlength: 15,
                    required: true
                },
                mdrPin: {
                    maxlength: 15,
                    required: true
                },
                mdrEmail: {
                    maxlength: 15,
                    required: true
                },
                
            },
            highlight: function(element) {
                $(element).closest('.form-group').addClass('has-error');
            },
            unhighlight: function(element) {
                $(element).closest('.form-group').removeClass('has-error');
            },
            errorElement: 'span',
            errorClass: 'help-block',
            errorPlacement: function(error, element) {
                if(element.parent('.input-group').length) {
                    error.insertAfter(element.parent());
                } else {
                    error.insertAfter(element);
                }
            }
        });
    	
    	/*
    	 * Initialize form validations
    	 */
    	$('#updateForm').validate({
            rules: {
            	
                mdrFname: {
                    maxlength: 15,
                    required: true
                },
                mdrNmane: {
                    maxlength: 15,
                    required: true
                },mdrFname: {
                    maxlength: 15,
                    required: true
                },
                mdrLname: {
                    maxlength: 15,
                    required: true
                },
                mdrAddress: {
                    maxlength: 15,
                    required: true
                },
                mdrCity: {
                    maxlength: 15,
                    required: true
                },
                mdrState: {
                    maxlength: 15,
                    required: true
                },
                mdrCountry: {
                    maxlength: 15,
                    required: true
                },
                mdrPin: {
                    maxlength: 15,
                    required: true
                },
                mdrEmail: {
                    maxlength: 15,
                    required: true
                },
            },
            highlight: function(element) {
                $(element).closest('.form-group').addClass('has-error');
            },
            unhighlight: function(element) {
                $(element).closest('.form-group').removeClass('has-error');
            },
            errorElement: 'span',
            errorClass: 'help-block',
            errorPlacement: function(error, element) {
                if(element.parent('.input-group').length) {
                    error.insertAfter(element.parent());
                } else {
                    error.insertAfter(element);
                }
            }
    	});

    });

	/*
	 * Click event for create button
	 * Creates new value of data being displayed in Modal form
	 * Refreshes data table on successful creation
	 * 
	 * Calls 
	 * refreshMyTable()
	 * 
	 * converter()
	 * <SerializedArray> - Serialized Array of Form Data
	 */
	$("#insertModerator").click(function(){
	//	event.preventDefault();
		if($('#insertForm').valid()) {
		formData = ($('#insertForm').serializeArray());
		$.ajax({
		    url : 'http://localhost:8080/easyskool/rest/Admin/insertModerator',
			type : 'POST',
			data : '{"user":"sumit","fields":'+ converter(formData)+ '}',
			dataType : 'json',
			async : false,
			contentType : "application/json; charset=utf-8",
			success : function(data,testStatus,jqXHR) {
				var json = jQuery.parseJSON(jqXHR.responseText);
					if(json.create == "success"){
						$("#myInsertModal").modal('hide');
						refreshMyTable();
						clearModalFormValues("insertForm");
					} else	{
						alert(json.create);
						alert(json.Message);
						alert(json.Cause);
					}
			},
			error : function(data,testStatus,jqXHR) {
				alert("reach");
				var json = jQuery.parseJSON(jqXHR.responseText);
				alert("statuscode" + json.status);
						alert(json.create);
						alert(json.Message);
						alert(json.Cause);
	
			}
	    });
		}
	});

	/*
	 * Click event for update button
	 * Updates value of currently selected row being displayed in Modal form
	 * Refreshes data table on successful updation
	 * 
	 * Calls 
	 * refreshMyTable()
	 * 
	 * converter()
	 * <SerializedArray> - Serialized Array of Form Data
	 */
	$('#updateForm').on('click', '#updateModerator', function(){
		   if($('#updateForm').valid()) {
			formData = ($('#updateForm').serializeArray());
					
					$.ajax({
						url : 'http://localhost:8080/easyskool/rest/Admin/updateModerator',
							type : 'POST',
							data : '{"user":"sumitupdate","whereClause" : {"sectionId" : '+ null +'},"updateClause":'+ converter(formData)+ '}',
							dataType : 'json',
							async : false,
							contentType : "application/json; charset=utf-8",
							success : function(data,testStatus,response) {
								var json = jQuery.parseJSON(response.responseText);
								if(json.update == "success"){
									$("#myUpdateModal").modal('hide');
									refreshMyTable();
									clearModalFormValues("updateForm");
								} else{
									alert("Error: ! "+ jqXHR.responseText);
								}
							}
						});
		   			}
	     });

    /*
     * Click event for delete selected rows
     * Deletes multiple rows after confirmation
     * Refreshes data table on successful deletion
     * 
     * Calls 
     * 
     * refreshMyTable()
     * 
     * tableRowToObj()
     * <tr> - Row to be converted to json
     */
    $('#deleteSelectedRows').click(function() {
    	var deleteSelectedRowsObj={};
    	deleteSelectedRowsObj.selectedModerators=[];

    	$("input:checkbox").each(function(){
    	    var $this = $(this);

    	    if($this.is(":checked")){
    	    	var curRowId = $this.closest('tr');
    	    	deleteSelectedRowsObj.selectedModerators.push(curRowId.children('td.aaCode').text());
    	    } 
    	});
    	
	    $('#confirmDelete').click(function() {
	    	$.ajax({
	       		url : 'http://localhost:8080/easyskool/rest/Admin/deleteSelectedModerators',
	   			type : 'POST',
	   			data : '{"user":"aa","whereClause" : { "aaCode" : [' +deleteSelectedRowsObj.selectedModerators.join(",")+']}}',
	   			dataType : 'json',
	   			async : false,
	   			contentType : "application/json; charset=utf-8",
	   			success : function(data,testStatus,response) {
	   				var json = jQuery.parseJSON(response.responseText);
	   				if(json.del == "success"){
	   					refreshMyTable();
	   				} else	{
					alert("Error: ! "+ jqXHR.responseText);
	   				}
	   			}
	       	});
	    	$("#myConfirmModal").modal('hide');
		});
    
	    $('#cancelDelete').click(function() {
	    	$("#myConfirmModal").modal('hide');
		});
    
    });
      
	/*
	 * Creates table with header row and pagination footer bar
	 * 
	 * Calls
	 * 
	 * createTableHeader()
	 * <String> - toAppend
	 * <String[]> - Table headers Array
	 * <boolean> - true to attach select all checkbox in header row 
	 */    
    function createMyTable() {
    	var toAppend = "";
    	//var tableId = "mytable";
    	var theaders = ["Moderator Code",
    	                "Firstname",
    	                "Middle Name",
    	                "Lastname",
    	                "Address",
    	                "City",
    	                "State",
    	                "Country",
    	                "Pin",
    	                "Email Id",
    	                "Created By",
    	                "Create Date",
    	                "Modified By",
    	                "Modified Date",
    	                "Update",
    	                "Delete"];
    	toAppend +=	"<table class='table form-fields table-striped tablesorter' id='mytable'>";
    	toAppend = createTableHeader(toAppend, theaders, true);
		toAppend = attachPaginationBarToTable(toAppend);
		toAppend += "</table>";
		
		$("#tableDiv").append(toAppend);
    }
    
    /*
     * Create table from data collected by json Retrieve
     * 
     * Remove old table using ID
     * Create new table
     * For each row
     *     Start table row
     *     Add Checkbox to row
     *     Convert json item to table columns
     *     Add Update button
     *     Add Delete button
     *     End Table Row
     * Refresh Table Sorter
     * Re-attach click event to Update, Delete buttons, Checkbox     
     *
     * Calls
     * 
     * startTableRow()
     * <String> - toAppend
     * <int> - Attr id of row
     * 
     * addCheckboxToTableRow()
     * <String> - toAppend
     * <String> - Attr name of checkbox
     * <int> - Attr id of checkbox
     * 
     * jsonItemToString()
     * <String> - toAppend
     * <json> - part of json item from database
     * <String[]> - Array of names of hidden columns ["sectionName","createdDate"]
     * 
     * addButtonWithModalToTable()
     * <String> - toAppend
     * <String> - Display String of button
     * <String> - Css class for button
     * <String> - Attr Id of button
     * <String> - Modal Name called by button in which data from current row is populated
     * 
     * addButtonWithoutModalToTable()
     * <String> - toAppend
     * <String> - Display String of button
     * <String> - Css class for button
     * <String> - Attr Id of button
     * 
     * endTableRow()
     * <String> - toAppend
     * 
     * refreshTableSorter()
     * 
     * attachClickEventToUpdateButton()
     * 
     * attachClickEventToDeleteButton()
     * 
     * attachClickEventToSelectAllCheckBox()
     * 
     * return <void>
     */
    function refreshMyTable()
    {
    	$.ajax({
    		url:'http://localhost:8080/easyskool/rest/Admin/getModerators',
    		type:'POST',
    		data: '{"user":"user","whereClause":'+null+'}',
    		dataType: 'json',
    		async: false,
    		contentType: "application/json; charset=utf-8",
    		success:function (data,testStatus,response) {
    			var jsondata =JSON.parse(response.responseText);
    			var toAppend = "";
    			var hiddenCols = [""];
    			
    			$("#mytable").remove();
    			createMyTable();
    			
    			$("#mytable").append("<tbody id='tbodyId'>");
    			$.each(jsondata, function(i, item) {
    				toAppend = "";
    				toAppend = startTableRow(toAppend, i);
    				toAppend = addCheckboxToTableRow(toAppend, 'checkboxselect', i);
    				toAppend = jsonItemToString(toAppend, item, hiddenCols);
    				toAppend = addButtonWithModalToTable(toAppend, 'Update', 'btn btn-info', 'update', 'myUpdateModal');
    				toAppend = addButtonWithoutModalToTable(toAppend, 'Delete', 'btn btn-danger', 'remove');
    				toAppend = endTableRow(toAppend);
    				$("#mytable").append(toAppend);
    			});
    			$("#mytable").append("</tbody>");
    		}
		});
    	
    	refreshTableSorter();
    	attachClickEventToUpdateButton();
    	attachClickEventToDeleteButton();
    	attachClickEventToSelectAllCheckBox();
    }
    
    /*
     * Refresh Table Sorter Widget after table content is changed
     * 
     * return <void>
     */
    function refreshTableSorter() {
    	
    	$(function() {

			$.extend($.tablesorter.themes.bootstrap, {
				// these classes are added to the table. To see other table classes available,
				// look here: http://twitter.github.com/bootstrap/base-css.html#tables
				table      : 'table table-bordered',
				caption    : 'caption',
				header     : 'bootstrap-header', // give the header a gradient background
				footerRow  : '',
				footerCells: '',
				icons      : '', // add "icon-white" to make them white; this icon class is added to the <i> in the header
				sortNone   : 'bootstrap-icon-unsorted',
				sortAsc    : 'icon-chevron-up glyphicon glyphicon-chevron-up',     // includes classes for Bootstrap v2 & v3
				sortDesc   : 'icon-chevron-down glyphicon glyphicon-chevron-down', // includes classes for Bootstrap v2 & v3
				active     : '', // applied when column is sorted
				hover      : '', // use custom css here - bootstrap class may not override it
				filterRow  : '', // filter row class
				even       : '', // odd row zebra striping
				odd        : ''  // even row zebra striping
			});

			// call the tablesorter plugin and apply the uitheme widget
			$("#mytable").tablesorter({
				// this will apply the bootstrap theme if "uitheme" widget is included
				// the widgetOptions.uitheme is no longer required to be set
				theme : "bootstrap",

				widthFixed: true,

				headerTemplate : '{content} {icon}', // new in v2.7. Needed to add the bootstrap icon!

				// widget code contained in the jquery.tablesorter.widgets.js file
				// use the zebra stripe widget if you plan on hiding any rows (filter widget)
				widgets : [ "uitheme", "filter", "zebra" ],

				widgetOptions : {
					// using the default zebra striping class name, so it actually isn't included in the theme variable above
					// this is ONLY needed for bootstrap theming if you are using the filter widget, because rows are hidden
					zebra : ["even", "odd"],

					// reset filters button
					filter_reset : ".reset"

					// set the uitheme widget to use the bootstrap theme class names
					// this is no longer required, if theme is set
					// ,uitheme : "bootstrap"

				}
			})
			.tablesorterPager({

				// target the pager markup - see the HTML block below
				container: $(".ts-pager"),

				// target the pager page select dropdown - choose a page
				cssGoto  : ".pagenum",

				// remove rows from the table to speed up the sort of large tables.
				// setting this to false, only hides the non-visible rows; needed if you plan to add/remove rows with the pager enabled.
				removeRows: false,

				// output string - default is '{page}/{totalPages}';
				// possible variables: {page}, {totalPages}, {filteredPages}, {startRow}, {endRow}, {filteredRows} and {totalRows}
				output: '{startRow} - {endRow} / {filteredRows} ({totalRows})'

			});

		});
		
		$(function(){

				// filter button demo code
				$('button.filter').click(function(){
					var col = $(this).data('column'),
						txt = $(this).data('filter');
					$('#mytable').find('.tablesorter-filter').val('').eq(col).val(txt);
					$('#mytable').trigger('search', false);
					return false;
				});

				// toggle zebra widget
				$('button.zebra').click(function(){
					var t = $(this).hasClass('btn-success');

					$('#mytable')
						.toggleClass('table-striped')[0]
						.config.widgets = (t) ? ["uitheme", "filter"] : ["uitheme", "filter", "zebra"];
					$(this)
						.toggleClass('btn-danger btn-success')
						.find('i')
						.toggleClass('icon-ok icon-remove glyphicon-ok glyphicon-remove').end()
						.find('span')
						.text(t ? 'disabled' : 'enabled');
					$('#mytable').trigger('refreshWidgets', [false]);
					return false;
				});
			});
    }
    
    /*
     * Attach click event to update button on table row
     * Populate values in Modal form from columns in current row
     * Needs to handle table column - dropdown, radiobutton, checkbox, date etc.
     * 
     *  Calls tableRowToModalForm()
     *  
     *  <tr> - Current table row
     *  <String> - Char('u') { ModalFormInputName(usectionId) - TableColName(sectionId) }
     *  <String> - Form name
     *  
     *  return <void>
     */
    function attachClickEventToUpdateButton() {
    	$('#mytable').on('click', '#update', function(){
        	tableRowToModalForm($(this).closest('tr'),'u','updateForm');
       });
    }
    
    /*
     * Attach click event to delete button on table row
     * Delete single row after confirm
     * Refresh Table after delete if successful
     * 
     * Calls refreshMyTable()
     * 
     * return <void>
     */
    function attachClickEventToDeleteButton() {
    	$('#mytable').on('click', '#remove', function(){
        	
        	var curRowId = $(this).closest('tr');
        	$("#myConfirmModal").modal('show');
        	
        	$('#confirmDelete').click(function() {
        		$("#myConfirmModal").modal('hide');
               	$.ajax({
               		url : 'http://localhost:8080/easyskool/rest/Admin/deleteModerator',
           			type : 'POST',
           			data : '{"user":"aa","whereClause" : { "aaCode" : '  + curRowId.children('td.aaCode').text() + '}}',
           			dataType : 'json',
           			async : false,
           			contentType : "application/json; charset=utf-8",
           			success : function(data,testStatus,response) {
           				var json = jQuery.parseJSON(response.responseText);
           				if(json.del == "success"){
           					refreshMyTable();
           				} else	{
        				alert("Error: ! "+ jqXHR.responseText);
           				}
           			}
               	});
               	
                
            });
        	
        	$('#cancelDelete').click(function() {
        		$("#myConfirmModal").modal('hide');
        	
        	});
        	
        });
    }
    
    /*
     * Attach click event to Select all checkbox
     * 
     * return <void>
     */
    function attachClickEventToSelectAllCheckBox() {
    	$('.form-fields').on('click', '#chkall', function(){
    		if(this.checked)
    			{
    				$('input[name=checkboxselect]').prop('checked', true);
    			} else {
    				$('input[name=checkboxselect]').prop('checked', false);
    			}
    	});
    }
    

    
    